//
//  DUVideoPlayer.m
//  APP
//
//  Created by duyujin1 on 2021/8/16.
//

#import "DUVideoPlayer.h"
#import <AVFoundation/AVFoundation.h>
#import "DUVideoCoverViewCell.h"

@interface DUVideoPlayer()
@property (nonatomic,strong)AVPlayerItem * videoItem;
@property (nonatomic,strong,readwrite)AVPlayer * avPlayer;
@property (nonatomic,strong)AVPlayerLayer * playLayer;
@end

@implementation DUVideoPlayer


+(DUVideoPlayer *)Player{
    static DUVideoPlayer * player;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player=[[DUVideoPlayer alloc] init];
    });
    return player;
}

-(void)dealloc{
    [self removeObserver:self forKeyPath:@"playOrPause"];
}

-(void)playVideoWithUrl:(NSString *)videoUrl attachView:(UIView *)attachView{
    //首先停止播放
    [self _stopToPlay];
    
    NSURL * videoURL=[NSURL URLWithString:videoUrl];
    AVAsset * asset=[AVAsset assetWithURL:videoURL];
    _videoItem=[AVPlayerItem playerItemWithAsset:asset];
    //KVO监听视频资源状态
    [_videoItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    //监听视频缓冲进度
    [_videoItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    //创建播放器
    _avPlayer=[AVPlayer playerWithPlayerItem:_videoItem];
    //监听播放进度
    [_avPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        NSLog(@"播放进度：%@",@(CMTimeGetSeconds(time)));
    }];
    //展示playerLayer
    _playLayer=[AVPlayerLayer playerLayerWithPlayer:_avPlayer];
    _playLayer.videoGravity=AVLayerVideoGravityResizeAspect;
    _playLayer.frame=attachView.bounds;
    [attachView.layer addSublayer:_playLayer];
    //[_avPlayer play];
    //接收播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_handlePlayEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
}

-(void)_stopToPlay{
    //移除监听
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_videoItem removeObserver:self forKeyPath:@"status"];
    [_videoItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
    //销毁播放器
    [_playLayer removeFromSuperlayer];
    _avPlayer=nil;
    _videoItem=nil;
}

-(void)_handlePlayEnd:playEndBlock{
    //回到第零秒
//    [_avPlayer seekToTime:CMTimeMake(0, 1)];
//    [_avPlayer play];
    //重新显示播放按钮
}

#pragma mark -KVO

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if([keyPath isEqualToString:@"status"]){
        if(((NSNumber *)[change objectForKey:NSKeyValueChangeNewKey]).integerValue==AVPlayerItemStatusReadyToPlay){
            //需要在状态变化后获取时间
            CMTime duration=_videoItem.duration;
            __unused CGFloat videoDuration= CMTimeGetSeconds(duration);
            //在合适的时机开始播放
            [_avPlayer play];
        }else{
            NSLog(@"");
        }
    }else if([keyPath isEqualToString:@"loadedTimeRanges"]){
        //缓冲进度监听
        NSLog(@"缓冲：%@",[change objectForKey:NSKeyValueChangeNewKey]);
    }
}


@end
